package com.reebake.ideal.message.mail.handler;

import cn.hutool.core.date.DateUtil;
import com.reebake.ideal.message.mail.service.MailSendService;
import com.reebake.ideal.message.core.MessageMediumTypeConstants;
import com.reebake.ideal.message.core.MessageStatusConstants;
import com.reebake.ideal.message.entity.MessageDeliveryDTO;
import com.reebake.ideal.message.entity.MessageDeliveryFeedbackDTO;
import com.reebake.ideal.message.event.MessageDeliveryEvent;
import com.reebake.ideal.message.event.MessageDeliveryFeedbackEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

@Component
@Slf4j
public class MailDeliveryEventListener {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private MailSendService mailSendService;

    @EventListener
    public void handle(MessageDeliveryEvent messageDeliveryEvent) {
        MessageDeliveryDTO messageDeliveryDTO = messageDeliveryEvent.getMessageDeliveryDTO();
        if(!MessageMediumTypeConstants.MAIL.equals(messageDeliveryDTO.getMediumType())){
            return;
        }
        String channelId = messageDeliveryDTO.getChannelId();
        String outTemplateId = messageDeliveryDTO.getOutTemplateId();
        Boolean isBatchSend = messageDeliveryDTO.getIsBatchSend();
        Boolean enableDelivery = messageDeliveryDTO.getEnableDelivery();
        String receiverIds = messageDeliveryDTO.getReceiverIds();
        String messageHistoryId = messageDeliveryDTO.getMessageHistoryId();
        String tile = messageDeliveryDTO.getTitle();
        String content = messageDeliveryDTO.getContent();
        LinkedHashMap<String, String> data = new LinkedHashMap<>();

        // TODO 构建附件
        String deliveryStatus = null, reason = null;
        try {
            mailSendService.sendMail(tile, content, null, receiverIds);
            deliveryStatus = MessageStatusConstants.DELIVERED;
        }catch (Exception e) {
            deliveryStatus = MessageStatusConstants.FAILURE;
            reason = e.getMessage();
            log.error("mail send error.", e);
        }

        MessageDeliveryFeedbackDTO messageDeliveryFeedbackDTO = new MessageDeliveryFeedbackDTO();
        messageDeliveryFeedbackDTO.setMessageHistoryId(messageHistoryId);
        messageDeliveryFeedbackDTO.setDeliveryTime(DateUtil.date());
        messageDeliveryFeedbackDTO.setDeliveryStatus(deliveryStatus);
        messageDeliveryFeedbackDTO.setReason(reason);
        applicationEventPublisher.publishEvent(new MessageDeliveryFeedbackEvent(this, messageDeliveryFeedbackDTO));
    }
}
